package com.onenine.app.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.util.SparseBooleanArray;
import android.view.View;

import com.onenine.app.R;
import com.onenine.app.adapter.MemberSelectAdapter;
import com.onenine.app.event.FinishEvent;
import com.onenine.app.event.RefreshEvent;
import com.onenine.app.fragment.FriendAttentionFragment;
import com.onenine.app.model.GroupMemberItem;
import com.onenine.app.model.MemberItem;
import com.onenine.app.request.GroupKickJoinRequest;
import com.onenine.app.request.GroupMemberRequest;
import com.onenine.app.response.FriendAttentionResponse;
import com.onenine.app.response.GroupMemberResponse;
import com.onenine.app.response.UserInfoResponse;
import com.onenine.app.utils.CDataProcessor;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.utils.UrlConfig;
import com.onenine.base.base.BasePageListActivity;
import com.onenine.base.okhttp.BaseResponse;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.Toasty;
import com.onenine.base.view.PullRefreshRecyclerView;
import com.onenine.chat.rongcloud.GroupCacheMgr;
import com.onenine.chat.rongcloud.RcUser;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import io.rong.message.GroupNotificationMessage;
import io.rong.message.InformationNotificationMessage;

/**
 * 创建时间：2018/7/4 0004 13:13
 * 创建人：fly
 * 功能描述：群组成员管理(拉人或踢人)
 */
public class GroupMemberMgrActivity extends BasePageListActivity {

    public static final byte INVITE = 0x01;
    public static final byte KICK = 0x10;
    private byte mMgrType; //拉人或踢人
    private String mGroupChatId;

    public static void launchActivity(Context context, String targetId, byte mgrType) {
        Intent intent = new Intent(context, GroupMemberMgrActivity.class);
        intent.putExtra("targetId", targetId);
        intent.putExtra("mgrType", mgrType);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_pull_refresh_layout;
    }

    @Override
    protected void initViews() {
        super.initViews();
        mMgrType = getIntent().getByteExtra("mgrType", INVITE);
        mGroupChatId = getIntent().getStringExtra("targetId");
        mToolbar.setRightTextVisible(false);
        mToolbar.setLeftTitle(R.string.cancel);
        mToolbar.setCenterTitle(mMgrType == INVITE ? R.string.invite_join_group : R.string.kick);
        mToolbar.setRightTitle(mMgrType == INVITE ? R.string.add : R.string.delete);
        mToolbar.setRightTitleBackground(RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.THEME_GRADIENT_CORNER_BG), true);
    }

    @Override
    protected void initData() {
        super.initData();
        loadPageData(1);
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        mToolbar.setOnRightClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inviteJoinKickGroup(mMgrType == INVITE);
            }
        });
    }

    /**
     * 群拉人或踢人
     */
    private void inviteJoinKickGroup(final boolean isInvite) {
        showLoading(R.string.submit_data_doing);
        final UserInfoResponse userInfo = RcUser.getInstance().getInfoResponse();
        final Pair<String, String> userPairs = getInviteMemberInfos();
        GroupKickJoinRequest request = new GroupKickJoinRequest();
        request.setGroupChatId(mGroupChatId);
        request.setUserId(RcUser.getInstance().getUserId());
        request.setTargetUserIds(userPairs.first);
        OkRequest.getInstance().withUrl(isInvite ? UrlConfig.INVITE_FRIEND_JOIN_GROUP : UrlConfig.KICK_GROUP_MEMBERS)
                .withRequest(request).doRequest(GroupMemberMgrActivity.class.getSimpleName(), new OkCallback<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response, String srcData) {
                dismissLoading();
                if (!response.isSuccess()) {
                    Toasty.showNormal(response.getMessage());
                    return;
                }
                if (isInvite) {
                    //拉人成功后发广播
                    String eventMsg = getString(R.string.invite_member_success_desc
                            , userInfo != null ? userInfo.getNickName() : "", userPairs.second);
                    InformationNotificationMessage message = InformationNotificationMessage.obtain(eventMsg);
                    message.setExtra(GroupNotificationMessage.GROUP_OPERATION_ADD);
                    CDataProcessor.insertInviteKickStatusMessage(mGroupChatId, message);
                    EventBus.getDefault().post(message);
                } else {
                    //踢人后发广播
                    String eventMsg = getString(R.string.kick_member_success_desc
                            , userInfo != null ? userInfo.getNickName() : "", userPairs.second);
                    InformationNotificationMessage message = InformationNotificationMessage.obtain(eventMsg);
                    message.setExtra(GroupNotificationMessage.GROUP_OPERATION_KICKED);
                    CDataProcessor.insertInviteKickStatusMessage(mGroupChatId, message);
                    EventBus.getDefault().post(message);
                }
                //清除群信息缓存，从网上重新拉取
                GroupCacheMgr.getInstance().deleteGroupCacheByGroupId(mGroupChatId);
                EventBus.getDefault().post(new FinishEvent(true));
                finish();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefreshEvent event) {
        if (event.type == DataType.REFRESH_MEMBER_SELECT_COUNT) {
            if (event.extraInt > 0) {
                mToolbar.setRightTextVisible(true);
                mToolbar.setRightTitle(String.format("确定(%d)", event.extraInt));
            } else {
                mToolbar.setRightTextVisible(false);
                mToolbar.setRightTitle("");
            }
        }
    }

    /**
     * 拼接人员id或姓名
     *
     * @return
     */
    private Pair<String, String> getInviteMemberInfos() {
        SparseBooleanArray mSelectArray = ((MemberSelectAdapter) mAdapter).getSelectArray();
        StringBuilder userIds = new StringBuilder();
        StringBuilder userNames = new StringBuilder();
        List<MemberItem> dataList = getData();
        for (int i = 0; i < mSelectArray.size(); i++) {
            if (mSelectArray.valueAt(i)) {
                MemberItem groupMember = dataList.get(mSelectArray.keyAt(i));
                userIds.append(groupMember.getUserId()).append(",");
                userNames.append(groupMember.getNickName()).append("、");
            }
        }
        if (userIds.toString().endsWith(",")) {
            userIds.deleteCharAt(userIds.length() - 1);
        }
        if (userNames.toString().endsWith("、")) {
            userNames.deleteCharAt(userNames.length() - 1);
        }
        return Pair.create(userIds.toString(), userNames.toString());
    }

    @Override
    protected Pair<PullRefreshRecyclerView, RecyclerView.Adapter> initPullRefreshView() {
        return new Pair(findViewById(R.id.pull_to_refresh_layout), new MemberSelectAdapter(getData()));
    }

    @Override
    protected void loadPageData(int pageNum) {
        if (mMgrType == INVITE) {
            getInviteMemberList();
        } else {
            getGroupMemberList();
        }
    }

    /**
     * 获取待拉好友分页列表
     */
    public void getInviteMemberList() {
        GroupMemberRequest request = new GroupMemberRequest(RcUser.getInstance().getUserId(), mGroupChatId);
        OkRequest.getInstance().withUrl(UrlConfig.GET_INVITE_FRIEND_LIST).withRequest(request)
                .doRequest(FriendAttentionFragment.class.getSimpleName(), new OkCallback<FriendAttentionResponse>() {
                    @Override
                    public void onResponse(FriendAttentionResponse response, String srcData) {
                        dismissRefreshStatus();
                        if (response.isSuccess()) {
                            notifyDataSuccess(response.getDataList());
                            mPullRefreshView.loadMoreEnd(true);
                        } else {
                            notifyDataFailure();
                        }
                    }
                });
    }

    /**
     * 查询成员列表
     */
    public void getGroupMemberList() {
        OkRequest.getInstance().withUrl(UrlConfig.GET_GROUP_MEMBER_LIST)
                .withRequest(new GroupMemberRequest(RcUser.getInstance().getUserId(), mGroupChatId))
                .doRequest(GroupMemberMgrActivity.class.getSimpleName(), new OkCallback<GroupMemberResponse>() {
                    @Override
                    public void onResponse(GroupMemberResponse response, String srcData) {
                        dismissRefreshStatus();
                        if (response.isSuccess()) {
                            notifyDataSuccess(filterSelfMember(response.getGroupMemberList()));
                            mPullRefreshView.loadMoreEnd(true);
                        } else {
                            notifyDataFailure();
                        }
                    }
                });
    }

    /**
     * 过滤自己
     *
     * @param groupMemberList
     */
    private List<GroupMemberItem> filterSelfMember(List<GroupMemberItem> groupMemberList) {
        String meUserId = RcUser.getInstance().getUserId();
        MemberItem meGroupMember = null;
        for (MemberItem groupMember : groupMemberList) {
            if (TextUtils.equals(groupMember.getUserId(), meUserId)) {
                meGroupMember = groupMember;
                break;
            }
        }
        if (meGroupMember != null) {
            groupMemberList.remove(meGroupMember);
        }
        return groupMemberList;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        OkRequest.getInstance().cancelTag(GroupMemberMgrActivity.class.getSimpleName());
    }

}
